<?php

use Yaf\Controller_Abstract;

/**
 * 基础控制器
 */
class BaseController extends Controller_Abstract
{
    /**
     * 成功相应的状态码
     * @return int
     */
    private function getSuccessCode(): int
    {
        return 0;
    }

    /**
     * JSON响应
     * @param int $code 响应码
     * @param string $msg 消息
     * @param array $data 数据
     * @return bool
     */
    final protected function json(int $code = 0, string $msg = 'ok', array $data = []): bool
    {
        $rs = [
            'code' => $code,
            'data' => empty($data) ? (object)$data : $data,
            'msg' => $msg
        ];
        $response = $this->getResponse();
        $response->setHeader('Content-Type', 'application/json; charset=utf-8');
        $response->setBody(json_encode($rs, JSON_UNESCAPED_UNICODE));
        return false;
    }

    /**
     * 成功响应
     * @param array $data
     * @return bool
     */
    final protected function data(array $data): bool
    {
        return $this->json($this->getSuccessCode(), 'ok', $data);
    }

    /**
     * 成功响应
     * @param string $msg
     * @param array $data
     * @return bool
     */
    final protected function success(string $msg = 'ok', array $data = []): bool
    {
        return $this->json($this->getSuccessCode(), $msg, $data);
    }

    /**
     * 失败响应
     * @param string $msg
     * @param int $code
     * @param array $data
     * @return bool
     */
    final protected function fail(string $msg = 'fail', int $code = 1, array $data = []): bool
    {
        return $this->json($code ?: 400, $msg, $data);
    }

    /**
     * 添加允许跨域的响应报文头
     */
    final protected function cors(): void
    {
        $response = $this->getResponse();
        $access = [
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Allow-Origin' => "*",
            'Access-Control-Allow-Methods' => '*',
            'Access-Control-Allow-Headers' => '*',
        ];
        foreach ($access as $key => $value) {
            $response->setHeader($key, $value);
        }
    }
}
